package com.yunxin.admin.system.infra.framework.security;

import com.yunxin.admin.system.infra.framework.security.userdetails.UserDetailsExternalService;
import com.yunxin.common.exception.BusinessException;
import com.yunxin.core.utils.infra.common.constant.ServerResultCode;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

/**
 * 短信验证码授权认证类
 *
 * @author zero°
 * @since 2023-11-24
 */
@Component
@RequiredArgsConstructor
public class SmsAuthenticationProvider implements AuthenticationProvider {

    private final UserDetailsExternalService userDetailsExternalService;


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SmsAuthenticationToken token = (SmsAuthenticationToken) authentication;
        UserDetails userDetails = userDetailsExternalService.loadUserByMobile((String) token.getPrincipal());
        accountCheck(userDetails);
        SmsAuthenticationToken result = new SmsAuthenticationToken(userDetails, userDetails.getAuthorities());
        result.setDetails(authentication.getDetails());
        return result;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return (SmsAuthenticationToken.class.isAssignableFrom(authentication));
    }

    /**
     * 账户检查
     * @param user user
     */
    private void accountCheck(UserDetails user){
        if (!user.isEnabled()) {
            throw new BusinessException(ServerResultCode.ADMIN_USER_STATUS_ERROR);
        }
    }

}